﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAP.Middleware.Connector;
using CM.BL.BE;
using System.Configuration;

namespace CM.DL.DALC.SAP
{
    public sealed class DALC
    {
        //Datos x default
        private static string _uName = "";
        private static string _passwd = "";
        private static string _server = getParamValue("SERVER");
        private static string _instance = getParamValue("INSTANCE");
        private static string _sysId = getParamValue("SYSID");
        private static string _langu = getParamValue("LANGU");
        private static string _mandt = getParamValue("MANDT");
        private static string _sapRouter = getParamValue("ROUTERSAP");

        public static string getParamValue(string key)
        {
            return ConfigurationManager.AppSettings[key.ToUpper()];
        }

        public static RfcConfigParameters getConfigParam(RfcConfigParametersBE objConn)
        {
            RfcConfigParameters foundDestination;
            foundDestination = new RfcConfigParameters();
            foundDestination.Add(RfcConfigParameters.Name, objConn.Id);
            foundDestination.Add(RfcConfigParameters.SAPRouter, (string.IsNullOrEmpty(objConn.SapRouter) ? _sapRouter : objConn.SapRouter));
            foundDestination.Add(RfcConfigParameters.AppServerHost, (string.IsNullOrEmpty(objConn.Server) ? _server : objConn.Server));
            foundDestination.Add(RfcConfigParameters.SystemNumber, (string.IsNullOrEmpty(objConn.Instance) ? _instance : objConn.Instance));
            foundDestination.Add(RfcConfigParameters.SystemID, (string.IsNullOrEmpty(objConn.SysId) ? _sysId : objConn.SysId));
            foundDestination.Add(RfcConfigParameters.User, (string.IsNullOrEmpty(objConn.Uname) ? _uName : objConn.Uname));
            foundDestination.Add(RfcConfigParameters.Password, (string.IsNullOrEmpty(objConn.Passwd) ? _passwd : objConn.Passwd));
            foundDestination.Add(RfcConfigParameters.Client, (string.IsNullOrEmpty(objConn.Mandt) ? _mandt : objConn.Mandt));
            foundDestination.Add(RfcConfigParameters.Language, (string.IsNullOrEmpty(objConn.Langu) ? _langu : objConn.Langu));
            foundDestination.Add(RfcConfigParameters.PoolSize, "5");
            foundDestination.Add(RfcConfigParameters.MaxPoolSize, "10");
            foundDestination.Add(RfcConfigParameters.IdleTimeout, "1");

            return foundDestination;
        }

        public static string getConnectionId(RfcConfigParametersBE pObjConn)
        {
            string retval = string.Empty; IRfcFunction function = null;
            RfcDestination dest; RfcConfigParameters cp;
            DestConfig dc = new DestConfig();
            try
            {
                cp = DALC.getConfigParam(pObjConn);
                try
                {
                    //RfcDestinationManager.UnregisterDestinationConfiguration(dc);
                    RfcDestinationManager.RegisterDestinationConfiguration(dc);
                }
                catch { }
                CredencialesController.Usuario = pObjConn;
                //objConn.Uname = pObjUsuarioWebBE.Usuario;
                //objConn.Passwd = pObjUsuarioWebBE.Clave;
                //objConn.Id = pObjUsuarioWebBE.guid;

                dc.AddOrEditDestination(cp);
                dest = RfcDestinationManager.GetDestination(CredencialesController.Usuario.Id);
                dest.Ping();
                //-- crear funciones en repositorio para que la invocación sea más rápida
                function = dest.Repository.CreateFunction("BAPI_PO_RELEASE");
                function = dest.Repository.CreateFunction("ZCM_MM_001");
            }
            catch (Exception ex)
            {
                dc.RemoveDestination(pObjConn.Id);
                retval = ex.Message;
            }
            finally
            {
                RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return retval;
        }

        public static string logOut(string pConnId)
        {
            string retval = string.Empty;
            DestConfig dc = new DestConfig();
            try
            {
                try
                {
                    RfcDestinationManager.RegisterDestinationConfiguration(dc);
                }
                catch { }
                try//fix para la ejecución en la pantalla inicio cuando aún no se han logeado.
                {
                    RfcDestination dest = RfcDestinationManager.GetDestination(pConnId);
                    dest.Repository.ClearAllMetadata();
                    dest.Parameters.Clear();
                }
                catch { }
                dc.RemoveDestination(pConnId);
            }
            catch (Exception ex)
            {
                retval = ex.Message;
            }
            finally
            {
                RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return retval;
        }

        /// <summary>
        /// Obtiene RfcDestination de CredencialesController; si no existe, crea uno nuevo y lo devuelve @@@
        /// </summary>
        public static RfcDestination getDestination()
        {
            RfcConfigParameters rfcConfP = new RfcConfigParameters();
            RfcConfigParametersBE objConn = new RfcConfigParametersBE();
            DestConfig dc = new DestConfig();
            RfcDestination dest;
            IRfcFunction function = null;
            try
            {
                try
                {
                    RfcDestinationManager.RegisterDestinationConfiguration(dc);
                }
                catch { }
                dest = RfcDestinationManager.GetDestination(CredencialesController.Usuario.Id);
                dest.Ping();
            }
            catch (RfcInvalidParameterException ex)
            {
                try
                {
                    //--no se encontró el ID especificado, se debe abrir una nueva conexión
                    objConn.Uname = CredencialesController.Usuario.Uname;
                    objConn.Passwd = CredencialesController.Usuario.Passwd;
                    objConn.Id = CredencialesController.Usuario.Id;

                    rfcConfP = DALC.getConfigParam(objConn);
                    dc.AddOrEditDestination(rfcConfP);
                    dest = RfcDestinationManager.GetDestination(CredencialesController.Usuario.Id);
                    dest.Ping();
                }
                catch (Exception ex2)
                {
                    dc.RemoveDestination(CredencialesController.Usuario.Id);
                    throw ex2;//lanza excepció para mostrar mensaje de error
                }
            }
            catch (Exception ex3)
            {
                dc.RemoveDestination(CredencialesController.Usuario.Id);
                throw ex3;//lanza excepció para mostrar mensaje de error
            }
            finally
            {
                RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return dest;
        }
    }
}
